package com.adong.web;

import com.adong.pojo.Book;
import com.adong.pojo.Page;
import com.adong.service.BookService;
import com.adong.service.impl.BookServiceImpl;
import com.adong.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author adong
 */
public class ClientBookServlet extends BaseServlet {

    private BookService bookService = new BookServiceImpl();

    /**
     * 首页正常的分页
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数pageNO和pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), 4);
        //调用BookService.page(pageNo,pageSize)
        Page<Book> page = bookService.page(pageNo, pageSize);
        page.setUrl("client/bookServlet?action=page");
        //保存page对象到request域中
        req.setAttribute("page", page);
        //请求转发到
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);

    }

    /**
     * 处理首页价格搜索的区间的分页设置
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数pageNO和pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), 4);
        int min = WebUtils.parseInt(req.getParameter("min"), 0); //没有传最小价格从0开始
        int max = WebUtils.parseInt(req.getParameter("max"), Integer.MAX_VALUE); //没有传最大价格从int最大值开始
        //调用BookService.page(pageNo,pageSize)
        Page<Book> page = bookService.pageByPrice(pageNo, pageSize, min, max);
        StringBuilder sb = new StringBuilder("client/bookServlet?action=pageByPrice");
        //判断价格输入框中是否有最小价格,有者添加进来
        if (req.getParameter("min") != null) {
            sb.append("&min=").append(req.getParameter("min"));
        }
        if (req.getParameter("max") != null) {
            sb.append("&max=").append(req.getParameter("max"));
        }
        page.setUrl(sb.toString());

        //保存page对象到request域中
        req.setAttribute("page", page);
        //请求转发到
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);

    }
}
